#coding:utf-8
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False #用来正常显示负号
# 读取数据，丢弃缺失值
df = pd.read_csv('data.csv',encoding='cp936')
df = df.dropna() #删除空值
#按月汇总
df1 = df[:]
df1['月'] = df1['日期'].map(lambda x: x[5:7])
df1 = df1.groupby('月',as_index=False).agg(np.sum)
print(df1)
# 生成营业额折线图
plt.figure(figsize=(8,4))  #创建大小为800*400绘图对象
plt.plot(df1['月'],df1['销量'],'b--',linewidth=1.0,label='营业额')
plt.xlabel('月份')   #设置X轴的文字
plt.ylabel('营业额（元）')   #设置Y轴的文字
plt.title('按月份汇总营业额折线图') #设置图表的标题
plt.legend() #显示图例
plt.grid(True)
plt.savefig('first.jpg')
plt.show()
# 按月统计，生成柱状图
plt.figure(figsize=(8,4))
plt.bar(df1['月'],df1['销量'])
plt.savefig('second.jpg')
plt.show()
# 查找涨幅最大的月份，写入文件
df2 = df1.drop('月', axis=1).diff()
m = df2['销量'].nlargest(1).keys()[0]
with open('maxMonth.txt', 'w') as fp:
    fp.write(df1.loc[m, '月'])
# 按季度统计，生成饼状图
plt.figure(figsize=(8,4))
one = df1[:3]['销量'].sum()
two = df1[3:6]['销量'].sum()
three = df1[6:9]['销量'].sum()
four = df1[9:12]['销量'].sum()
print([one, two, three, four])
labels = ["一季度", "二季度", "三季度", "四季度"]
facts = [one, two, three, four]
plt.pie(x = facts, labels = labels, autopct = "%.0f%%", shadow= True)
plt.savefig('third.jpg')
plt.show()